package net.herrialde.geo.util;

import java.net.URLEncoder;

import net.herrialde.geo.bean.GeoDirection;
import net.herrialde.geo.bean.Portal;
import net.herrialde.geo.bean.Probintzia;
import net.herrialde.geo.bean.Udalerria;

import org.json.JSONArray;
import org.json.JSONObject;

public class GoogleUtil {
	
	private static String GOOGLE_LOCATION_TYPE = "";
	private static String GOOGLE_FORMATTED_ADDRESS = "";
	private static boolean GOOGLE_IS_OK = false;

	// geolocalización inversa con Google Maps API
	// devuelve un array con {provincia, municipio, codPostal}
	public static String[] getGoogleMaps(String lat, String lon) {
		String[] datos = new String[3];
		String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="
				+ lat + "," + lon + "&sensor=false";
		try {
			String resp = RemoteUtil.getJson(url);
			JSONArray jar = new JSONObject(resp).getJSONArray("results");
			JSONObject json = jar.getJSONObject(0);
			JSONArray j0 = json.getJSONArray("address_components");
			for (int i=0; i < j0.length(); i++) {
				String tipo = j0.getJSONObject(i).getString("types");
				if (tipo.contains("administrative_area_level_2"))
					datos[0] = j0.getJSONObject(i).getString("long_name");
				else if (tipo.contains("locality"))
					datos[1] = j0.getJSONObject(i).getString("long_name");
				else if (tipo.contains("postal_code"))
					datos[2] = j0.getJSONObject(i).getString("long_name");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return datos;
	}
	
	public static String[] getGoogleMapsCoords(String direccion) {
		GOOGLE_LOCATION_TYPE = "*";
		GOOGLE_FORMATTED_ADDRESS = "*";
		//String direccion = calle + " " + portal + ", " + municipio;
		String[] latlng = null;
		try {
			String sURL = "http://maps.google.com/maps/api/geocode/json?sensor=false&language=es&region=es&address=" + 
					URLEncoder.encode(direccion, "UTF-8");
			
			String json = RemoteUtil.getJson(sURL);
			
			JSONObject jsonObj = new JSONObject(json);
			String google_status = jsonObj.getString("status").toString();
			if (!google_status.equals("OK"))
				GOOGLE_IS_OK = false;
			else
				GOOGLE_IS_OK = true;
			
			
			JSONArray resultArry = jsonObj.getJSONArray("results");
			
			if ((resultArry != null) && (resultArry.length() > 0)) {
				JSONObject obj0 = resultArry.getJSONObject(0);
			
				String address = obj0.getString("formatted_address").toString();
				if (address != null) {
					GOOGLE_FORMATTED_ADDRESS = address;
				}
			
				JSONObject geometry = obj0.getJSONObject("geometry");
				GOOGLE_LOCATION_TYPE = geometry.getString("location_type");
				if (!GOOGLE_LOCATION_TYPE.equals("ROOFTOP"))
					GOOGLE_IS_OK = false;
				System.out.println("status: " + google_status + "\t" + GOOGLE_LOCATION_TYPE + "\t" + direccion);
			
				JSONObject location = geometry.getJSONObject("location");
				latlng = new String[2];
				latlng[0] = "" + location.getDouble("lat");
				latlng[1] = "" + location.getDouble("lng");
			}
			
		} catch (Exception e) {
            e.printStackTrace();
        }
		return latlng;
	}
	
	/**
	 * Busca las coordenadas de una dirección en Google Maps API
	 * @param dir
	 */
	public static String searchGoogleMapsDir(GeoDirection dir) {
		String latlong = null;
		String direccion = "";
		Udalerria udal = dir.getUdalerria();
		Portal portal = dir.getPortal();
		Probintzia prov = dir.getProbintzia();
		direccion = udal.getName() + ", " + portal.getNumero() + ", " + udal.getName();
		System.out.println("***DGA*** Dirección: " + direccion);
		String[] arlatlong = getGoogleMapsCoords(direccion);
		if (arlatlong != null) {
			latlong = arlatlong[0] + "," + arlatlong[1];
		}
		return latlong;
	}

}
